package com.qys.livesMall.app.user.scheduledTask;

import cn.hutool.core.date.DateTime;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qys.livesMall.app.user.model.dto.sys.UserJuniorInfoVO;
import com.qys.livesMall.app.user.model.entity.*;
import com.qys.livesMall.app.user.service.*;
import com.qys.livesMall.common.utils.DateUtils;
import com.qys.livesMall.finance.enums.AccountBusinessTypeEnum;
import com.qys.livesMall.finance.model.entity.user.FinanceUserAccount;
import com.qys.livesMall.finance.model.entity.user.FinanceUserAccountDetail;
import com.qys.livesMall.finance.service.FinanceUserAccountDetailService;
import com.qys.livesMall.finance.service.FinanceUserAccountService;
import jakarta.annotation.Resource;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Component("UserStatisticsInfoTask")
@Slf4j
@AllArgsConstructor
public class UserStatisticsInfoScheduledTask {

    @Resource
    private UserStatisticsTeamService userStatisticsTeamService;
    @Resource
    private UserShopStatisticsService userShopStatisticsService;
    @Resource
    private IH2AppUserRechargeWithdrawalsService appUserRechargeWithdrawalsService;
    @Resource
    private UserStatisticsInfoService userStatisticsInfoService;
    @Resource
    private FinanceUserAccountService financeUserAccountService;
    @Resource
    private FinanceUserAccountDetailService financeUserAccountDetailService;
    @Resource
    private IH2AppUserService ih2AppUserService;
    @Resource
    private IH2AppUserRechargeWithdrawalsService rechargeWithdrawalsService;
    @Resource
    private AppUserRelationService appUserRelationService;
    @Resource
    private UserStatisticsDayLogService userStatisticsDayLogService;
    /**
     * 定时任务每天修正团数据
     */
    public void updateUserTeamTask() {
        updateUserTeam(null);
    }

    public void updateUserTeam(List<Long> teamIds) {
        //查询团用户全部数据
        List<UserStatisticsTeam> list=null;
        if (CollectionUtils.isNotEmpty(teamIds)){
            LambdaQueryWrapper<UserStatisticsTeam> queryWrapper=new LambdaQueryWrapper<>();
            queryWrapper.in(UserStatisticsTeam::getTeamId,teamIds);
            list= userStatisticsTeamService.list(queryWrapper);
        }else {
            list= userStatisticsTeamService.list();
        }
        if (CollectionUtils.isEmpty(list)){
            return;
        }
        //查询全部用户
        List<H2AppUser> usersAll=ih2AppUserService.userAll();
        //3级以内 真实  正常状态 用户
        List<String> effectiveUsersAll=usersAll.stream().filter(a-> null !=a.getUserLevelId() && a.getUserSysType()==1 && a.getUserLevelId().intValue()<3  && null != a.getStatus() && a.getStatus()==0).map(H2AppUser::getId).toList();
        //用户收益编码
        List<String> codes = AccountBusinessTypeEnum.getUserIncomeCode();
        //用户收益详细数据
        List<FinanceUserAccountDetail> financeUserAccountDetails=financeUserAccountDetailService.getbyCode(codes);
        Map<Long,List<FinanceUserAccountDetail>> financeUserAccountDetailMap=financeUserAccountDetails.stream().collect(Collectors.groupingBy(s -> s.getUserId()));
        List<UserShopStatistics> userShopStatisticsList=userShopStatisticsService.getUserShopStatisticsAll();
        //真实  正常状态 用户
        List<String> realUsersAll=usersAll.stream().filter(a->  a.getUserSysType()==1 && null != a.getStatus() && a.getStatus()==0).map(H2AppUser::getId).toList();
        for (UserStatisticsTeam userShopStatisticsTeam:list){
            //注册人数
            List<UserShopStatistics> userStatisticsList=userShopStatisticsList.stream().filter(a->null != a.getTeamId() && a.getTeamId().intValue() == userShopStatisticsTeam.getTeamId().intValue()).collect(Collectors.toList());
            userShopStatisticsTeam.setRegisterNum(userStatisticsList.size());
            if (CollectionUtils.isNotEmpty(userStatisticsList)){
                BigDecimal result=financeUserAccountService.getSumUserByteam(userShopStatisticsTeam.getTeamId());
                if (null!=result){
                    userShopStatisticsTeam.setTeamBalance(result);
                }
                //团人数
                Long num=userStatisticsList.stream().filter(a->realUsersAll.contains(a.getUserId().toString())).count();
                userShopStatisticsTeam.setNum(num.intValue());

                List<Long> ids= userStatisticsList.stream().map(UserShopStatistics::getUserId).collect(Collectors.toList());
                List<H2AppUserRechargeWithdrawals> h2AppUserRechargeWithdrawals=appUserRechargeWithdrawalsService.listAgreeByIds(ids);
                //充值
                BigDecimal teamRecharge=h2AppUserRechargeWithdrawals.stream().filter(a->a.getType().equals(AccountBusinessTypeEnum.RECHARGE.getCode())).map(a->a.getRealAmount()).reduce(
                        BigDecimal.ZERO,BigDecimal::add
                );
                userShopStatisticsTeam.setTeamRecharge(teamRecharge);
                //提现
                BigDecimal teamWithdrawal=h2AppUserRechargeWithdrawals.stream().filter(a->a.getType().equals(AccountBusinessTypeEnum.WITHDRAWAL.getCode())).map(a->a.getRealAmount()).reduce(
                        BigDecimal.ZERO,BigDecimal::add
                );
                userShopStatisticsTeam.setTeamWithdrawal(teamWithdrawal);
                //团队充提差额
                BigDecimal teamDifference=teamRecharge.subtract(teamWithdrawal);
                userShopStatisticsTeam.setTeamDifference(teamDifference);

                List<H2AppUserRechargeWithdrawals> waitList= appUserRechargeWithdrawalsService.getlistWaitByIds(ids);
                BigDecimal waitWithdrawal=waitList.stream().map(a->a.getAmount()).reduce(
                        BigDecimal.ZERO,BigDecimal::add
                );
                userShopStatisticsTeam.setWaitWithdrawal(waitWithdrawal);
                //总累计收益
                BigDecimal sumCumulative=BigDecimal.ZERO;
                //过期人数
                int expireNumber=0;
                //30天过期人数
                int expireRecent=0;
                int recentAdd = 0;
                //30天 日期
                DateTime dateTime=DateUtils.offsetDay(DateUtils.date(),-30);
                for (Long userid:ids){
                    List<FinanceUserAccountDetail> accountDetails=financeUserAccountDetailMap.get(userid);
                    if (CollectionUtils.isEmpty(accountDetails)){
                        continue;
                    }
                    BigDecimal cumulative= accountDetails.stream().map(a->a.getAmountIncurred()).reduce(BigDecimal.ZERO,BigDecimal::add);
                    sumCumulative=sumCumulative.add(cumulative);
                    //获取最近一条数据
                    accountDetails=accountDetails.stream()
                            .sorted(Comparator.comparing(FinanceUserAccountDetail::getPayDate))
                            .collect(Collectors.toList());
                    FinanceUserAccountDetail financeUserAccountDetail= accountDetails.get(0);
                    JSONObject jsonObject= JSON.parseObject(financeUserAccountDetail.getPayAfter());
                    BigDecimal availableBalance= new BigDecimal(jsonObject.get("availableBalance").toString());
                    if (effectiveUsersAll.contains(userid.toString()) && availableBalance.compareTo(new BigDecimal(20))<0){
                        expireNumber++;
                        if (financeUserAccountDetail.getPayDate().compareTo(dateTime.toLocalDateTime())>0){
                            expireRecent++;
                        }
                    }else  if (effectiveUsersAll.contains(userid.toString())
                            && availableBalance.compareTo(new BigDecimal(20))>=0
                            && financeUserAccountDetail.getPayDate().compareTo(dateTime.toLocalDateTime())>0){
                        recentAdd++;
                    }
                }
                userShopStatisticsTeam.setCumulative(sumCumulative);
                userShopStatisticsTeam.setExpireNumber(expireNumber);
                userShopStatisticsTeam.setExpireRecent(expireRecent);
                userShopStatisticsTeam.setRecentAdd(recentAdd);
            }
        }
        userStatisticsTeamService.updateBatchById(list);
    }

    /**
     * 定时任务每天修正用户数据  充值、提现、收益 、用户下级数量
     */
    public void updateUserInfoTask() {
        updateUserStatisticsInfo(null);
    }
    public void updateUserStatisticsInfo(List<Long> userIds) {
        List<UserStatisticsInfo> userStatisticsInfos=null;
        if (CollectionUtils.isNotEmpty(userIds)){
            LambdaQueryWrapper<UserStatisticsInfo> queryWrapper=new LambdaQueryWrapper<>();
            queryWrapper.in(UserStatisticsInfo::getUserId,userIds);
            userStatisticsInfos= userStatisticsInfoService.list(queryWrapper);
        }else {
            userStatisticsInfos=userStatisticsInfoService.list();
        }
        //用户收益明细数据
        List<String> codes = AccountBusinessTypeEnum.getUserIncomeCode();
        //主播收益
        List<String> anchorCodes=new ArrayList<>();
        anchorCodes.add(AccountBusinessTypeEnum.ORDER_PROFIT_ANCHOR_GET.getCode());
        anchorCodes.add(AccountBusinessTypeEnum.LIVE_GIFT_ANCHOR_GET.getCode());
        List<String> newCodes =new ArrayList<>();
        newCodes.addAll(codes);
        newCodes.addAll(anchorCodes);
        List<FinanceUserAccountDetail> newFinanceUserAccountDetails=financeUserAccountDetailService.getbyCode(newCodes);
        List<FinanceUserAccountDetail> financeUserAccountDetails=newFinanceUserAccountDetails.stream().filter(a->codes.contains(a.getCode())).toList();
        List<FinanceUserAccountDetail> anchorFinanceUserAccountDetails = newFinanceUserAccountDetails.stream().filter(a->anchorCodes.contains(a.getCode())).toList();
        //用户收益Map
        Map<Long,List<FinanceUserAccountDetail>> financeUserAccountDetailMap=financeUserAccountDetails.stream().collect(Collectors.groupingBy(s -> s.getUserId()));

        //用户下级信息
        List<Long> userids=userStatisticsInfos.stream().map(UserStatisticsInfo::getUserId).collect(Collectors.toList());
        List<UserJuniorInfoVO> userJuniorInfoVOS=rechargeWithdrawalsService.getJuniorInfo(userids);
        Map<Long,UserJuniorInfoVO> map=userJuniorInfoVOS.stream().collect(Collectors.toMap(UserJuniorInfoVO::getUserId, Function.identity(),(a, a2) -> a2));
        for (UserStatisticsInfo userStatisticsInfo:userStatisticsInfos){
            //用户总累计收益
            List<FinanceUserAccountDetail> accountDetails=financeUserAccountDetailMap.get(userStatisticsInfo.getUserId());
            if (CollectionUtils.isNotEmpty(accountDetails)){
                BigDecimal cumulative= accountDetails.stream().map(a->a.getAmountIncurred()).reduce(BigDecimal.ZERO,BigDecimal::add);
                userStatisticsInfo.setCumulative(cumulative);
            }
            //用户主播收益
            if (CollectionUtils.isNotEmpty(anchorFinanceUserAccountDetails)){
                BigDecimal anchorOrderIncome=anchorFinanceUserAccountDetails.stream().filter(a->a.getUserId().equals(userStatisticsInfo.getUserId()) && a.getCode().equals(AccountBusinessTypeEnum.ORDER_PROFIT_ANCHOR_GET.getCode()))
                        .map(FinanceUserAccountDetail::getAmountIncurred).reduce(BigDecimal.ZERO, BigDecimal::add);
                userStatisticsInfo.setAnchorOrderIncome(anchorOrderIncome);
                BigDecimal anchorGiftIncome=anchorFinanceUserAccountDetails.stream().filter(a->a.getUserId().equals(userStatisticsInfo.getUserId()) && a.getCode().equals(AccountBusinessTypeEnum.LIVE_GIFT_ANCHOR_GET.getCode()))
                        .map(FinanceUserAccountDetail::getAmountIncurred).reduce(BigDecimal.ZERO, BigDecimal::add);
                userStatisticsInfo.setAnchorGiftIncome(anchorGiftIncome);
            }else {
                userStatisticsInfo.setAnchorOrderIncome(BigDecimal.ZERO);
                userStatisticsInfo.setAnchorGiftIncome(BigDecimal.ZERO);
            }
            userStatisticsInfo.setDifference(userStatisticsInfo.getRecharge().subtract(userStatisticsInfo.getWithdrawal()));
            UserJuniorInfoVO userJuniorInfoVO=map.get(userStatisticsInfo.getUserId());
            if (null != userJuniorInfoVO){
                userStatisticsInfo.setDirectNumber(userJuniorInfoVO.getDirectNum());
                userStatisticsInfo.setTwoNumber(userJuniorInfoVO.getSecondGrandNum());
                userStatisticsInfo.setThreeNumber(userJuniorInfoVO.getThirdGrandNum());
                userStatisticsInfo.setThreeWithdrawalAmount(userJuniorInfoVO.getWithdrawalAmount());
                userStatisticsInfo.setRechargeMoney(userJuniorInfoVO.getRechargeAmount());
                userStatisticsInfo.setRegisterNum(userJuniorInfoVO.getRegisterNum());
                userStatisticsInfo.setAllNumber(userJuniorInfoVO.getAllNumber());
            }

            //充值提现信息
            List<H2AppUserRechargeWithdrawals> h2AppUserRechargeWithdrawals=appUserRechargeWithdrawalsService.listAgreeByIds(Arrays.asList(userStatisticsInfo.getUserId()));
            userStatisticsInfo.setRechargeNumber(0);
            userStatisticsInfo.setRecharge(BigDecimal.ZERO);
            userStatisticsInfo.setWithdrawalNumber(0);
            userStatisticsInfo.setWithdrawal(BigDecimal.ZERO);
            userStatisticsInfo.setDifference(BigDecimal.ZERO);
            if (CollectionUtils.isEmpty(h2AppUserRechargeWithdrawals)){
               continue;
            }
            //充值
            Long rechargeNumber =h2AppUserRechargeWithdrawals.stream().filter(a->a.getType().equals(AccountBusinessTypeEnum.RECHARGE.getType())).count();
            if (null != rechargeNumber){
                userStatisticsInfo.setRechargeNumber(rechargeNumber.intValue());
                BigDecimal recharge=h2AppUserRechargeWithdrawals.stream().filter(a->a.getType().equals(AccountBusinessTypeEnum.RECHARGE.getType())).map(a->a.getRealAmount()).reduce(
                        BigDecimal.ZERO,BigDecimal::add
                );
                userStatisticsInfo.setRecharge(recharge);
            }
            //提现
            Long withdrawalNumber=h2AppUserRechargeWithdrawals.stream().filter(a->a.getType().equals(AccountBusinessTypeEnum.WITHDRAWAL_APPLY_FOR.getType())).count();
            if (null!=withdrawalNumber){
                userStatisticsInfo.setWithdrawalNumber(withdrawalNumber.intValue());
                BigDecimal withdrawal=h2AppUserRechargeWithdrawals.stream().filter(a->a.getType().equals(AccountBusinessTypeEnum.WITHDRAWAL_APPLY_FOR.getType())).map(a->a.getRealAmount()).reduce(
                        BigDecimal.ZERO,BigDecimal::add
                );
                userStatisticsInfo.setWithdrawal(withdrawal);
            }
            userStatisticsInfo.setDifference(userStatisticsInfo.getRecharge().subtract(userStatisticsInfo.getWithdrawal()));
        }
        userStatisticsInfoService.updateBatchById(userStatisticsInfos);
    }
    /**
     * 定时任务每天修正下级用户数据 余额 过期
     */
    public void updateUserSubordinateInfoTask() {
        updateUserSubordinateInfo(null);
    }

    public void updateUserSubordinateInfo(List<Long> userIds) {
        //修补偿少了UserStatisticsInfo用户数据
        List<UserStatisticsInfo> userStatisticsInfos=null;
        if (CollectionUtils.isNotEmpty(userIds)){
            LambdaQueryWrapper<UserStatisticsInfo> queryWrapper=new LambdaQueryWrapper<>();
            queryWrapper.in(UserStatisticsInfo::getUserId,userIds);
            userStatisticsInfos= userStatisticsInfoService.list(queryWrapper);
        }else {
            List<H2AppUser> users=ih2AppUserService.getWeek();
            userStatisticsInfos=userStatisticsInfoService.list();
            List<Long> registerUserids=userStatisticsInfos.stream().map(UserStatisticsInfo::getUserId).toList();
            //查询UserStatisticsInfo不存在的用户数据
            List<H2AppUser> registerUser=users.stream().filter(a-> ! registerUserids.contains(Long.valueOf(a.getId()))).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(registerUser)){
                List<UserStatisticsInfo> addUser=new ArrayList<>();
                for (H2AppUser h2AppUser:registerUser){
                    UserStatisticsInfo userStatisticsInfo=new UserStatisticsInfo();
                    userStatisticsInfo.setUserId(Long.valueOf(h2AppUser.getId()));
                    addUser.add(userStatisticsInfo);
                }
                if (CollectionUtils.isNotEmpty(addUser)){
                    userStatisticsInfoService.saveBatch(addUser);
                    userStatisticsInfos=userStatisticsInfoService.list();
                }
            }
        }
        List<Long> firstChargeUsers=userStatisticsInfos.stream().filter(a->a.getFirstCharge() !=null).map(UserStatisticsInfo::getUserId).toList();
        LocalDateTime dateTime=DateUtils.offsetDay(DateUtils.date(),-30).toLocalDateTime();
        //用户余额
        List<FinanceUserAccount> list=financeUserAccountService.listByUserIds(null);
        Map<Long, FinanceUserAccount> financeUserAccountmap =list.stream().collect(Collectors.toMap(FinanceUserAccount::getUserId,Function.identity(),(a, a2) -> a2));
        List<UserStatisticsDayLog> incomeDayLogs=userStatisticsDayLogService.getTodayToType(2);
        for (UserStatisticsInfo userStatisticsInfo:userStatisticsInfos){
            //修正用户余额信息
            FinanceUserAccount financeUserAccount=financeUserAccountmap.get(userStatisticsInfo.getUserId());
            if (null != financeUserAccount){
                userStatisticsInfo.setBalance(financeUserAccount.getAvailableBalance());
            }
            //1~3代
            List<H2AppUser> h2AppUsers=appUserRelationService.getLowerLevels(userStatisticsInfo.getUserId(),Arrays.asList(1,2,3));
            if (CollectionUtils.isEmpty(h2AppUsers)){
                userStatisticsInfo.setRecentAdd(0);
                userStatisticsInfo.setExpireNumber(0);
                userStatisticsInfo.setRecentExpireNumber(0);
            }else {
               List<String> threeUserIds = h2AppUsers.stream().map(H2AppUser::getId).toList();
               if (CollectionUtils.isNotEmpty(incomeDayLogs)){
                   userStatisticsInfo.setThreeCumulativeAmount(userStatisticsInfos.stream().
                           filter(a->threeUserIds.contains(a.getUserId()) && a.getCumulative() !=null).map(UserStatisticsInfo::getCumulative).reduce(BigDecimal.ZERO,BigDecimal::add));
               }else {
                   userStatisticsInfo.setThreeCumulativeAmount(BigDecimal.ZERO);
               }
            }
            // 真实用户、正常用户、充值用户、3级内用户
            List<H2AppUser> effectiveUser=h2AppUsers.stream().filter(u->u.getUserSysType()==1
                            && u.getStatus()==0
                            && firstChargeUsers.contains(userStatisticsInfo.getUserId())
                            && u.getUserLevelId()<3
                    ).toList();

            Long recentAdd=effectiveUser.stream().filter(u->u.getCreateTime().compareTo(dateTime)>=0).count();
            userStatisticsInfo.setRecentAdd(recentAdd.intValue());

            Long expireNumber=effectiveUser.stream().filter(u->u.getCreateTime().compareTo(dateTime)>=0
                    && financeUserAccount.getAvailableBalance().compareTo(new BigDecimal("20"))==-1).count();
            userStatisticsInfo.setExpireNumber(expireNumber.intValue());

            Long recentExpireNumber=effectiveUser.stream().filter(u->financeUserAccount.getAvailableBalance().compareTo(new BigDecimal("20"))==-1).count();
            userStatisticsInfo.setRecentExpireNumber(recentExpireNumber.intValue());
            //1~n 代
            List<H2AppUser> allH2AppUsers=appUserRelationService.getLowerLevels(userStatisticsInfo.getUserId());
            if (CollectionUtils.isEmpty(allH2AppUsers)){
                userStatisticsInfo.setSubordinateExpireNumber(0);
            }
            // 真实用户、正常用户、充值用户、3级内用户
            List<H2AppUser> allEffectiveUser=allH2AppUsers.stream().filter(u->u.getUserSysType()==1
                    && u.getStatus()==0
                    && firstChargeUsers.contains(userStatisticsInfo.getUserId())
                    && u.getUserLevelId()<3
            ).toList();
            Long subordinateExpireNumber=allEffectiveUser.stream().filter(u->u.getCreateTime().compareTo(dateTime)>=0
                    && financeUserAccount.getAvailableBalance().compareTo(new BigDecimal("20"))==-1).count();
            userStatisticsInfo.setSubordinateExpireNumber(subordinateExpireNumber.intValue());
        }
        userStatisticsInfoService.updateBatchById(userStatisticsInfos);
    }

    public void updateUserChildInfoTask() {
        int i=1;
        List<UserStatisticsDayLog> list=userStatisticsDayLogService.getTodayToType(null);
        List<UserStatisticsDayLog> userList=list.stream().filter(a-> a.getType() ==0).toList();
        Map<Long,UserStatisticsDayLog> teamMap=list.stream().filter(a-> a.getType() ==2).collect(Collectors.toMap(UserStatisticsDayLog::getRelevanceId,Function.identity()));
        List<UserStatisticsInfo> userStatisticsInfos=userStatisticsInfoService.list();
        if (CollectionUtils.isEmpty(userStatisticsInfos)){
            return;
        }
        updateUserChildInfo(userStatisticsInfos,userList,teamMap);
        userStatisticsDayLogService.saveOrUpdateBatch(teamMap.values());
    }
    /**
     * 更新用户统计表中子级统计
     * @param allUserStatisticsInfos
     */
    public void updateUserChildInfo(List<UserStatisticsInfo> allUserStatisticsInfos, List<UserStatisticsDayLog> userList,Map<Long,UserStatisticsDayLog> teamMap){
        List<Long> ids= allUserStatisticsInfos.stream().map(UserStatisticsInfo::getUserId).toList();
        List<H2AppUserRechargeWithdrawals> waitList= appUserRechargeWithdrawalsService.getlistWaitByIds(ids);
        Map<String,List<H2AppUserRechargeWithdrawals>> waitWithdrawalMap=waitList.stream().collect(Collectors.groupingBy(H2AppUserRechargeWithdrawals::getUserId));
        //重新赋值待提现金额
        for (UserStatisticsInfo userStatisticsInfo:allUserStatisticsInfos) {
            List<H2AppUserRechargeWithdrawals> infos=waitWithdrawalMap.get(userStatisticsInfo.getUserId());
            if (CollectionUtils.isNotEmpty(infos)){
                BigDecimal pendingWithdrawal=infos.stream().map(a->a.getAmount()).reduce(BigDecimal.ZERO,BigDecimal::add);
                userStatisticsInfo.setPendingWithdrawal(pendingWithdrawal);
            }else {
                userStatisticsInfo.setPendingWithdrawal(BigDecimal.ZERO);
            }
        }
        for (UserStatisticsInfo userStatisticsInfo:allUserStatisticsInfos) {
            //用户团收益
            UserStatisticsDayLog userStatisticsDayLog = teamMap.get(userStatisticsInfo.getUserId());
            if (null == userStatisticsDayLog){
                userStatisticsDayLog=new UserStatisticsDayLog();
                userStatisticsDayLog.setType(2);
                userStatisticsDayLog.setDataTime(DateUtils.dateTimeNow());
                userStatisticsDayLog.setRelevanceId(userStatisticsInfo.getUserId());
            }
            //当前用户下3级用户ID
            List<Long> uIds=appUserRelationService.getUserLowerLevels(userStatisticsInfo.getUserId(),Arrays.asList(1,2,3));
            List<UserStatisticsInfo> threeUserIds=allUserStatisticsInfos.stream().filter(a->uIds.contains(a.getUserId())).toList();
            //123代操作
            if (CollectionUtils.isNotEmpty(threeUserIds)){
                //123代充值金额
                BigDecimal threeRechargeAmount= threeUserIds.stream().filter(a->null!=a.getRecharge()).map(UserStatisticsInfo::getRecharge)
                        .reduce(BigDecimal.ZERO,BigDecimal::add);
                userStatisticsInfo.setThreeRechargeAmount(threeRechargeAmount);
                //123代提现金额
                BigDecimal threeWithdrawalAmount= threeUserIds.stream().filter(a->null!=a.getWithdrawal()).map(UserStatisticsInfo::getWithdrawal)
                        .reduce(BigDecimal.ZERO,BigDecimal::add);
                userStatisticsInfo.setThreeWithdrawalAmount(threeWithdrawalAmount);
                //123代复冲金额
                BigDecimal threeRecoilAmount= threeUserIds.stream().filter(a->null!=a.getRechargeMoney()).map(UserStatisticsInfo::getRechargeMoney)
                        .reduce(BigDecimal.ZERO,BigDecimal::add);
                userStatisticsInfo.setThreeRecoilAmount(threeRecoilAmount);
                //123代充提差
                userStatisticsInfo.setThreeDifferenceamount(threeRechargeAmount.subtract(threeWithdrawalAmount));
                //123代待审核提现
                BigDecimal threePendingWithdrawal= threeUserIds.stream().filter(a->null!=a.getPendingWithdrawal()).map(UserStatisticsInfo::getPendingWithdrawal)
                        .reduce(BigDecimal.ZERO,BigDecimal::add);
                userStatisticsInfo.setThreePendingWithdrawal(threePendingWithdrawal);

                BigDecimal todayIncome=BigDecimal.ZERO;
                if (CollectionUtils.isNotEmpty(userList)){
                    todayIncome=userList.stream().filter(a->threeUserIds.contains(a.getRelevanceId())).map(UserStatisticsDayLog::getTodayIncome).reduce(BigDecimal.ZERO,BigDecimal::add);
                }
                userStatisticsDayLog.setTodayIncome(todayIncome);
                teamMap.put(userStatisticsInfo.getUserId(),userStatisticsDayLog);
                //累计团收益
                userStatisticsInfo.setThreeCumulativeAmount(threeUserIds.stream().filter(a-> a.getCumulative() !=null).map(UserStatisticsInfo::getCumulative).reduce(BigDecimal.ZERO,BigDecimal::add));
            }else {
                userStatisticsDayLog.setTodayIncome(BigDecimal.ZERO);
                teamMap.put(userStatisticsInfo.getUserId(),userStatisticsDayLog);
                userStatisticsInfo.setThreeCumulativeAmount(BigDecimal.ZERO);
            }
            List<Long> allIds=appUserRelationService.getUserLowerLevels(userStatisticsInfo.getUserId());
            List<UserStatisticsInfo> allUserIds=allUserStatisticsInfos.stream().filter(a->allIds.contains(a.getUserId())).toList();
            //全部子集操作1~n
            if (CollectionUtils.isNotEmpty(allUserIds)){
                //1~n代充值金额
                BigDecimal subordinateRechargeAmount= allUserIds.stream().filter(a->null!=a.getRecharge()).map(UserStatisticsInfo::getRecharge)
                        .reduce(BigDecimal.ZERO,BigDecimal::add);
                userStatisticsInfo.setSubordinateRechargeAmount(subordinateRechargeAmount);
                //1~n代提现金额
                BigDecimal subordinateWithdrawalAmount= allUserIds.stream().filter(a->null!=a.getWithdrawal()).map(UserStatisticsInfo::getWithdrawal)
                        .reduce(BigDecimal.ZERO,BigDecimal::add);
                userStatisticsInfo.setSubordinateWithdrawalAmount(subordinateWithdrawalAmount);
                //123代充提差
                userStatisticsInfo.setSubordinateDifferenceamount(subordinateRechargeAmount.subtract(subordinateWithdrawalAmount));
                //1~n代复冲金额
                BigDecimal subordinateRecoilAmount= allUserIds.stream().filter(a->null!=a.getRechargeMoney()).map(UserStatisticsInfo::getRechargeMoney)
                        .reduce(BigDecimal.ZERO,BigDecimal::add);
                userStatisticsInfo.setSubordinateRecoilAmount(subordinateRecoilAmount);
            }
            if (null == userStatisticsInfo.getFirstCharge() && null != userStatisticsInfo.getRechargeNumber()  && userStatisticsInfo.getRechargeNumber()>0){
                H2AppUserRechargeWithdrawals h2AppUserRechargeWithdrawals=appUserRechargeWithdrawalsService.getEarliestRechargeBYUserId(userStatisticsInfo.getUserId());
                userStatisticsInfo.setFirstCharge(h2AppUserRechargeWithdrawals.getAuditTime());
            }
        }
        userStatisticsInfoService.updateBatchById(allUserStatisticsInfos);
    }
}
